package main

import (
	"fmt"
	"io"
	"log"
	"os"
	"path/filepath"
	"strings"
	"syscall"
	"time"
)

var appDataPath string

func main() {
	//logsRecordOperate()
	fmt.Println("ssk测试卸载")
	//log.Println("ssk测试卸载")
	cmdOpenAdminExeOpeate()
}

func InitAppDataPath() {
	cache := os.Getenv("HOME")
	Product := "Uninstall"
	app := "Logs"
	ProductApp := strings.Title(Product) + strings.Title(app)
	appDataPath = filepath.Join(cache, ProductApp)
	_ = os.MkdirAll(appDataPath, os.ModePerm)
}

func logsRecordOperate() {
	//这里是日志的有关操作
	InitAppDataPath()
	var logFile *os.File
	relog := func(time time.Time) {
		log.SetOutput(os.Stdout)
		tag := "Uninstall"
		//if 0 != *ginPort {
		//	tag += "-" + xutil.ToString(*ginPort)
		//}
		if logFile != nil {
			_ = logFile.Close()
			_ = os.Rename(logFile.Name(), strings.ReplaceAll(logFile.Name(), ".txt", "   "+time.Format("02 15.04.05")+".txt"))
			logFile = nil
		}
		var err error
		logFile, err = os.OpenFile(filepath.Join(appDataPath, "log-"+tag+"-"+time.Format("2006-01-02")+".txt"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
		if err == nil {
			log.SetOutput(io.MultiWriter(logFile, os.Stdout))
			RedirectStderr(logFile)
		}
	}
	
	log.SetPrefix("\r\n")
	log.SetFlags(log.Lmicroseconds)
	now := time.Now()
	relog(now)
}

var (
	kernel32         = syscall.NewLazyDLL("kernel32.dll")
	procSetStdHandle = kernel32.NewProc("SetStdHandle")
)

func setStdHandle(stdhandle int32, handle syscall.Handle) error {
	r0, _, e1 := syscall.Syscall(procSetStdHandle.Addr(), 2, uintptr(stdhandle), uintptr(handle), 0)
	if r0 == 0 {
		if e1 != 0 {
			return error(e1)
		}
		return syscall.EINVAL
	}
	return nil
}
func RedirectStderr(f *os.File) {
	err := setStdHandle(syscall.STD_ERROR_HANDLE, syscall.Handle(f.Fd()))
	if err != nil {
		log.Println("Failed to redirect stderr to file:", err)
	}
	// SetStdHandle does not affect prior references to stderr
	os.Stderr = f
}
func cmdOpenAdminExeOpeate() {
	/*
		flag.CommandLine = flag.NewFlagSet(os.Args[0], 2)
		admin := flag.Bool("admin", false, "管理员权限")
		unrcm := flag.Bool("unContextMenu", false, "卸载菜单")
	
		if *unrcm {
			if !*admin {
				adminExeerror := xutil.AdminExec(xutil.ShellExecute{
					FileName:   "XdemoLite.exe", // xutil.AppExe(),
					Parameters: "uninstall",
					ShowCmd:    0,
				})
				fmt.Println("错误是：", adminExeerror)
				time.Sleep(2 * time.Second)
			} else {
				xutil.UnregisterPluginMenu()
				//xutil.UnregisterContextMenu()
			}
			return
		}
	*/
	
	//adminExeerror := xutil.AdminExec(xutil.ShellExecute{
	//	FileName:   "XdemoLite.exe", // xutil.AppExe(),
	//	Parameters: "uninstall",
	//	ShowCmd:    0,
	//})
	//fmt.Println("错误是：", adminExeerror)
	//log.Println("错误是：", adminExeerror)
}
